{% extends 'admin/layout/base.html.twig' %}

{% block stylecontent %}
    <style type="text/css" media="screen">
        
    </style>
{% endblock %}

{% block content %}

<div class="main" style="height:100%;">
    <!-- MAIN CONTENT -->
    <div class="main-content" style="height:100%;">
        <div class="container-fluid" style="height:100%;">
            <!-- OVERVIEW -->
            <div class="row" style="height:100%;">
                <!-- left content -->   
                <div class="col-md-3" style="overflow-y:auto; height:100%;">
                    <div class="">
                        <h3 class="page-title" style="float:left;">Create Page</h3>
                        <a style="float:right;" class="btn btn-primary" id="submit-btn" onclick="formSubmit()">Submit</a>
                        <div class="scrollmargin" style="height:10px;clear:both;"></div>
                    </div>
                    <!-- page info -->
                    <div class="panel panel-headline">
                        <div class="panel-heading">
                            <h4 class="panel-title">Page info</h4>
                        </div>
                        <div class="panel-body">
                            <div class="alert alert-danger alert-dismissible alert-window" style="display:none;" role="alert">
                                <button type="button" class="close alert-close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                <i class="fa fa-times-circle"></i> <span class="warner-msg">Your account has been suspended</span>
                            </div>
                            <div class="input-group">
                                <span class="input-group-addon">Title</span>
                                <input value="{{page?page.name:''}}" class="form-control input-title" placeholder="Please enter a title" name="name" type="text">
                                <input value="{{page?page.id:''}}" class="form-control input-id"  name="id" type="hidden">
                            </div><br>
                            <div class="input-group">
                                <span class="input-group-addon">Cover Image</span>
                                <input value="{{page?page.picurl:''}}" class="form-control input-picurl" placeholder="Please enter a image's path"  name="picurl" type="text">
                            </div><br>
                            <div class="input-group">
                                <span class="input-group-addon">Sort Value</span>
                                <input value="{{page?page.sort:''}}" class="form-control input-sort" placeholder="Please enter a sort value"  name="sort" type="text">
                            </div><br>
                            <div class="input-group">
                                <span class="input-group-addon">Category</span>
                                <select class="form-control input-lg input-cate">
                                    {% for category in categorys %}
                                        <option {% if (page and page.category.id == category.id) %} selected {% endif %} value="{{category.id}}">{{category.name}}</option>
                                    {% endfor %}
                                </select>
                            </div><br>
                            <div class="input-group">
                                <span class="input-group-addon">Active</span>
                                    <label class="fancy-radio" style="margin-top:5px;padding-left:20px;display:inline-block;">
										<input name="active" value="1" type="radio" {% if (page and page.active == 1) %} checked {% endif %}>
										<span style="display:inline;"><i></i>TRUE</span>
                                       
									</label>
                                    <label class="fancy-radio" style="margin-top:5px;padding-left:20px;display:inline-block;">
                                        <input name="active" value="0" type="radio" {% if (page and page.active == 0) %} checked {% endif %}>
										<span style="display:inline;"><i></i>FALSE</span>
									</label>
                            </div>
                        </div>
                    </div>

                    <!-- images -->
                    <div class="panel panel-headline">
                        <div class="panel-heading">
                            <h4 class="panel-title" style="float:left;">Image Management</h4>
                            <a style="float:right;" class="btn btn-primary" id="filePicker"><i class="fa fa-plus-square"></i>&nbsp;Choose Images</a>
                            <div class="scrollmargin" style="height:10px;clear:both;"></div>
                        </div>
                        <div class="panel-body">
                            <div class="image-list" id="uploader">
                                {% for image in images %}
                                    {% if image %}
                                        <div class="alert alert-info alert-dismissible" role="alert">
                                            <button type="button" class="close delete-image"><span aria-hidden="true">&times;</span></button>
                                            <img class="image-manage" src="{{image}}"/>
                                            <div class="img-info">
                                                <p>Path: {{image}}</p>
                                                <input class="images" type="hidden" value='{{image}}' name="images" />
                                            </div>
                                        </div>
                                    {% endif %}
                                {% endfor %}
                            </div>
                            <a class="btn btn-primary" id="upBtn">Upload</a>
                        </div>
                        
                    </div>

                    <!-- common files -->
                    <div class="panel panel-headline">
                        <div class="panel-heading">
                            <h4 class="panel-title">Common Css files</h4>
                        </div>
                        <div class="panel-body">
                            <pre>/common/reset.css</pre>
                            <pre>https://cdn.bootcss.com/Swiper/4.2.6/css/swiper.min.css</pre>
                        </div>
                        <div class="panel-heading">
                            <h4 class="panel-title">Common Js files</h4>
                        </div>
                        <div class="panel-body">
                            <pre>https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js</pre>
                            <pre>https://cdn.bootcss.com/Swiper/4.2.6/js/swiper.min.js</pre>
                            <pre>/common/basejs.js</pre>
                        </div>
                        <div class="panel-heading">
                            <h4 class="panel-title">Customer Service Link</h4>
                        </div>
                        <div class="panel-body">
                            <pre>Click Event: onclick="_MEIQIA('showPanel')"</pre>
                            <pre>Link : https://static.meiqia.com/dist/standalone.html?_=t&eid=107666</pre>
                        </div>
                        <div class="panel-heading">
                            <h4 class="panel-title">Customer Service JS</h4>
                        </div>
                        <div class="panel-body">
                            <pre>
&lt;script&gt;
    (function (m, ei, q, i, a, j, s) {
        m[i] = m[i] || function () {
            (m[i].a = m[i].a || []).push(arguments)
        };
        j = ei.createElement(q),
            s = ei.getElementsByTagName(q)[0];
        j.async = true;
        j.charset = 'UTF-8';
        j.src = 'https://static.meiqia.com/dist/meiqia.js?_=t';
        s.parentNode.insertBefore(j, s);
    })(window, document, 'script', '_MEIQIA');
    _MEIQIA('entId', 107666);
&lt;/script&gt;
                            </pre>
                         </div>
                    </div>
                    <!-- api -->
                    <div class="panel panel-headline">
                        <div class="panel-heading">
                            <h4 class="panel-title">Api Manual</h4>
                        </div>
                        <div class="panel-body">
                            <div class="panel">
                                <div class="panel-heading">
                                    <h5 class="panel-title">CAPTCHA</h5>
                                </div>
                                <div class="panel-body">
                                    URL
                                    <pre> {{url('captcha')}}</pre>
                                    Paramer
                                    <pre>
width  #int  nullable
height  #int  nullable</pre>
                                    Example
                                    <pre>&lt;img src="{{url('captcha')}}?width=250&height=100&math=0.001"&gt;</pre>
                                </div>
                            </div>
                            <div class="panel">
                                <div class="panel-heading">
                                    <h5 class="panel-title">Send SMS</h5>
                                </div>
                                <div class="panel-body">
                                    URL
                                    <pre> {{url('sendSms')}}</pre>
                                    Paramer
                                    <pre>
phone  #int  require 
code  #string  require</pre>
                                    Method
                                    <pre>POST</pre>
                                    Response
                                    <pre>
errno  #int  0success &gt;0 error 
message  #string  </pre>
                                </div>
                            </div>
                            <div class="panel">
                                <div class="panel-heading">
                                    <h5 class="panel-title">Form Submit</h5>
                                </div>
                                <div class="panel-body">
                                    URL
                                    <pre> {{url('checkCode')}}</pre>
                                    Paramer
                                    <pre>
name  #string  require                                     
phone  #int  require 
code  #string  require
topic   #string  require  pagetitle
content  #string  nullable</pre>
                                    Method
                                    <pre>POST</pre>
                                    Response
                                    <pre>
errno  #int  0success &gt;0 error 
message  #string  </pre>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- right content --> 
                <div class="col-md-9" style="overflow-y:auto; height:100%;">
                    <div class="page-title">
                        <label class="fancy-radio" style="display:inline-block">
                            <input name="type" value="1" type="radio" checked>
                            <span><i></i>PC</span>
                        </label>&nbsp;&nbsp;&nbsp;&nbsp;
                        <label class="fancy-radio" style="display:inline-block">
                            <input name="type" value="2" type="radio">
                            <span><i></i>Mobile</span>
                        </label>
                    </div>
                    <div id="sellInfo1" class="panel panel-headline pc-code">
                        <div class="panel-heading">
                            <h3 class="panel-title">PC</h3>
                        </div>
                        <div class="panel-body">
                            <div class="row" style="margin-bottom:-180px;">
                                <div class="transformed">
                                    <div class="wrapper">
                                        <textarea class="form-control import-pc-css" placeholder="Import Css files" rows="5">{{page?page.pcCssImport:''}}</textarea>
                                        <textarea class="form-control import-pc-js" placeholder="Import Js files" rows="10">{{page?page.pcJsImport:''}}</textarea>
                                        <pre id="editor1">{{page?page.pcCss:'/*# PC CSS */'}}</pre>
                                        <pre id="editor3">{{page?page.pcJs:'<!-- PC JS -->'}}</pre> 
                                        <pre id="editor2">{{page?page.pcContent:'<!-- PC HTML -->'}}</pre>
                                    </div>
                                    <div class="scrollmargin"></div>
                                </div>
                            </div>
                        </div>
                        <div class="panel panel-headline" >
                            <div class="panel-heading">
                                <h3 class="panel-title">Preview</h3>
                            </div>
                            <div class="panel-body">
                                <div class="row preview-p">
                                    <iframe id="preview1" class="preview" src=""></iframe>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div id="sellInfo2" class="panel panel-headline mobile-code" style="display:none">
                        <div class="panel-heading">
                            <h3 class="panel-title">Mobile</h3>
                        </div>
                        <div class="panel-body">
                            <div class="row" style="margin-bottom:-180px;">
                                <div class="transformed">
                                    <div class="wrapper">
                                        <textarea class="form-control import-mobile-css" placeholder="Import Css files" rows="5">{{page?page.mCssImport:''}}</textarea>
                                        <textarea class="form-control import-mobile-js" placeholder="Import Js files" rows="10">{{page?page.mJsImport:''}}</textarea>
                                        <pre id="editor4">{{page?page.mCss:'/*# Mobile CSS */'}}</pre>
                                        <pre id="editor6">{{page?page.mJs:'<!-- Mobile JS -->'}}</pre> 
                                        <pre id="editor5">{{(page and page.mContent)?page.mContent:'<!-- Mobile HTML -->'}}</pre>
                                    </div>
                                    <div class="scrollmargin"></div>
                                </div>
                            </div>
                        </div>
                        <div class="panel panel-headline" >
                            <div class="panel-heading">
                                <h3 class="panel-title">Preview</h3>
                            </div>
                            <div class="panel-body">
                                <div class="row preview-p">
                                    <iframe id="preview2" class="preview" src=""></iframe>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                </div>
            </div>
            <!-- END OVERVIEW -->
        </div>
    </div>
    <!-- END MAIN CONTENT -->
</div>
   
{% endblock %}

{% block jscript %}
<script src="/admin/scripts/ace/ace.js"></script>
<script>

    var editor1 = ace.edit("editor1");
    editor1.setOptions({
        hasCssTransforms: true,
        theme: "ace/theme/kuroir",
        mode: "ace/mode/css",
        minLines: 16,
        wrap: true,
        autoScrollEditorIntoView: true,
    });
    
    var editor2 = ace.edit("editor2");
    editor2.setOptions({
        hasCssTransforms: true,
        theme: "ace/theme/tomorrow_night_eighties",
        mode: "ace/mode/html",
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: false,
        minLines: 20,
        wrap: true
    });
    
    var editor3 = ace.edit("editor3");
    editor3.setOptions({
        hasCssTransforms: true,
        theme: "ace/theme/kuroir",
        mode: "ace/mode/javascript",
        minLines: 16,
        wrap: true
    });
    var editor4 = ace.edit("editor4");
    editor4.setOptions({
        hasCssTransforms: true,
        theme: "ace/theme/kuroir",
        mode: "ace/mode/css",
        minLines: 16,
        wrap: true,
    });
    
    var editor5 = ace.edit("editor5");
    editor5.setOptions({
        hasCssTransforms: true,
        theme: "ace/theme/tomorrow_night_eighties",
        mode: "ace/mode/html",
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: false,
        minLines: 20,
        wrap: true,
    });
    
    var editor6 = ace.edit("editor6");
    editor6.setOptions({
        hasCssTransforms: true,
        theme: "ace/theme/kuroir",
        mode: "ace/mode/javascript",
        minLines: 16,
        wrap: true,
    });
    var preview1 = $("#preview1");
    var preview2 = $("#preview2");
    $("input[name=type]").click(function(){console.log(123);
        switch($("input[name=type]:checked").attr("value")){
            case "1":
                $("#sellInfo2").hide();
                $("#sellInfo1").show();
                break;
            case "2":
                $("#sellInfo1").hide();
                $("#sellInfo2").show();
                break;
            default:
                break;
        }
    });
    editor1.on("input", updatePreview1);
    editor2.on("input", updatePreview1);
    editor4.on("input", updatePreview2);
    editor5.on("input", updatePreview2);
    function updatePreview1() {
        var code ='<meta charset="UTF-8">'+ $(".import-pc-css").val()+"<style>" + editor1.getValue().replace('/uploads/pages/','http://zhuanti.local/uploads/pages/') + "</style>"+editor2.getValue().replace('/uploads/pages/','http://zhuanti.local/uploads/pages/');
        preview1.attr('src',"data:text/html," + encodeURIComponent(code));
        console.log(code);
    }
    updatePreview1();
    function updatePreview2() {
        var code = '<meta charset="UTF-8">'+$(".import-mobile-css").val()+"<style>" + editor4.getValue().replace('/uploads/pages/','http://zhuanti.local/uploads/pages/') + "</style>"+editor5.getValue().replace('/uploads/pages/','http://zhuanti.local/uploads/pages/');
        preview2.attr('src',"data:text/html," + encodeURIComponent(code));
        console.log(code);
    }
    updatePreview2();
</script>
<script type="text/javascript" src="/admin/scripts/webuploader-0.1.5/webuploader.js"></script>
<script type="text/javascript">
	var uploader = WebUploader.create({
        // 选完文件后，是否自动上传。
        auto: false,

        // swf文件路径
        swf: '/admin/scripts/webuploader-0.1.5/js/Uploader.swf',

        // 文件接收服务端。
        server: '{{path("admin_upload")}}',

        // 选择文件的按钮。可选。
        pick: '#filePicker',

        // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
        resize: false,

        // 只允许选择图片文件。
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png,svg',
            mimeTypes: 'image/*'
        }
    });
    // 当有文件被添加进队列的时候
    uploader.on( 'fileQueued', function( file ) {
        console.log(file);
        var $li =  $('<div id="' + file.id + '" class="alert alert-info alert-dismissible" role="alert">' +
                        '<button type="button" class="close delete-image"><span aria-hidden="true">&times;</span></button>'+
                        '<img class="image-manage" src="/admin/img/apple-icon.png"/>' +
                        '<div class="img-info">'+
                            '<p>Name: ' + file.name + '</p>' +
                            '<p>Size: ' + file.size + 'kb </p>' +
                            '<div class="progress">' +
                                '<div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">' +
                                    '<span class="sr-only">0% Complete</span>' +
                                '</div>' +
                                '<div class="error"></div>' +
                            '</div>' +
                            '<input class="images" type="hidden" value="" name="images[]" />' +
                        '</div>' +
                    '</div>'),
            $img = $li.find('img');
        $("#uploader").append($li);
        // 创建缩略图
        // thumbnailWidth x thumbnailHeight 为 100 x 100
        uploader.makeThumb( file, function( error, src ) {
            if ( error ) {
                $img.replaceWith("<span>can't preview</span>");
                return;
            }
            $img.attr( 'src', src );
        }, 100, 100 );
    });
    // 文件上传过程中创建进度条实时显示。
    uploader.on( 'uploadProgress', function( file, percentage ) {
        console.log(percentage);
        var $li = $( '#'+file.id ),
            $percent = $li.find('.progress div');
        var percentvalue = percentage * 100;
        $percent.css( 'width', percentvalue + '%' );
        $percent.attr( 'aria-valuenow', percentvalue);
        $percent.find('span').html(percentvalue + '% Complete');
    });
    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    uploader.on( 'uploadSuccess', function( file , res) {
        console.log(res);
        var $li = $( '#'+file.id ),
            $success = $li.find('div.progress');
        if(res.errno==0){
            $success.before('<p style="word-wrap: break-word;">Path:<br>'+ res.path +'</p>');
            $success.remove();
            $li.find('.images').attr('value',res.path);
        } else {
            $success.html('<span class="label label-danger">upload failed</span>');
        }
    });
    // 文件上传失败，显示上传出错。
    uploader.on( 'uploadError', function( file ) {
        var $li = $( '#'+file.id ),
            $error = $li.find('div.progress');

        $error.html('<span class="label label-danger">upload failed</span>');
    });
    //start upload
    $("#upBtn").click(function(){
        uploader.upload();
    })
    $("body").on('click','.delete-image',function(){
        var _this = $(this),
         path = _this.parent().find('.images').val();
        console.log(path);
        layer.confirm('Delete anyway?', {
            title:"Note",
            btn: ['Sure','Cancel'] //按钮
            }, function(){
                var index = layer.load(1, {
                 shade: [0.1,'#fff'] 
                });
                $.post("{{path('admin_delete_file')}}",{file:path},function(result){
                    layer.close(index);
                    layer.msg('Success !', {icon: 1});
                    _this.parent().remove();
                });
            });
    })
    //close warning alert window 
    $(".alert-close").click(function(){
        $(this).parent().hide();
    })
    //alert warning window
    function alertWarning(msg){
        $(".warner-msg").text(msg);
        $(".alert-window").show();
    }

    //form submit handle
    function formSubmit(){
        var title = $(".input-title").val();
        if(!title){
            alertWarning("The title is required!");
            return false;
        }
        var pccss = editor1.getValue();
        var pchtml = editor2.getValue();
        var pcjs = editor3.getValue();
        if(pccss=='/*# PC CSS */'){
            alertWarning("The css code is required!");
            return false;
        }
        if(pchtml=='<!-- PC HTML -->'){
            alertWarning("The html code is required!");
            return false;
        }
        if(pcjs=='<!-- PC JS -->'){
            alertWarning("The js code is required!");
            return false;
        }
        $(".alert-window").hide();
        var category = $(".input-cate").val(),
            active = $("input[name='active']:checked").val(),
            sort = $(".input-sort").val(),
            picurl = $(".input-picurl").val(),
            pccssimport=$(".import-pc-css").val(),
            pcjsimport=$(".import-pc-js").val(),
            mcssimport=$(".import-mobile-css").val(),
            mjsimport=$(".import-mobile-js").val(),
            mcss = editor4.getValue(),
            mhtml = editor5.getValue()=='<!-- Mobile HTML -->'?'':editor5.getValue(),
            mjs = editor6.getValue(),
            images=[],
            index=0
            id = $(".input-id").val();
            
            $(".images").each(function(i,e){
                $(e).val() && (images[index]=$(e).val(),index++);
            });
            console.log(category,active,sort,images,pccssimport,pcjsimport,mcssimport,mjsimport,mcss,mhtml,mjs);

        //return false;

        //submit
        $.ajax({
            url: "{{path('storePage')}}",
            type: 'POST',
            dataType: 'json',
            data: {
                pccss:pccss,
                pchtml:pchtml,
                pcjs:pcjs,
                title:title,
                category:category,
                active:active,
                sort:sort,
                pccssimport:pccssimport,
                pcjsimport:pcjsimport,
                mcssimport:mcssimport,
                mjsimport:mjsimport,
                mcss:mcss,
                mhtml:mhtml,
                mjs:mjs,
                images:JSON.stringify(images),
                id:id,
                picurl:picurl
            },
            success: function(res){
                console.log(res);
                if(res.errno==0){
                    layer.msg('Success');
                    setTimeout("location.href='{{path("admin_dashboard")}}';",1000);  
                } else {
                    layer.msg('错误，请核实表单！');
                }
            },
            error: function(){
                
            }
        })
    }


</script>
	

{% endblock %}

